﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace SiteParser.Core
{
	public class MarkerHtmlIterator : RegexpHtmlIterator
	{
		private readonly Regex markerRegex;
		private string currentValue;
		private Match previousMatch;

		internal MarkerHtmlIterator(string htmlContent, HtmlNavigationExpression expression, IExpressionBuilder expressionBuilder, string markerRegexPattern)
			: base(htmlContent, expression, expressionBuilder)
		{
			if (string.IsNullOrEmpty(markerRegexPattern)) {
				throw new ArgumentNullException("markerRegexPattern");
			}

			markerRegex = new Regex(markerRegexPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
		}

		public override string SelectedValue {
			get {
				if (Success) {
					int startIndex = previousMatch != null ? previousMatch.Index : 0;
					int endIndex = currentMatch != null && currentMatch.Success ? currentMatch.Index : htmlContent.Length;

					return endIndex > startIndex ? htmlContent.Substring(startIndex, endIndex - startIndex) : string.Empty;
				} else {
					return null;
				}
			}
		}

		public override bool MoveNext() {
			if (currentMatch == null) {
				currentMatch = markerRegex.Match(htmlContent);
			} else {
				previousMatch = currentMatch;
				currentMatch = currentMatch.NextMatch();
			}

			return Success;


			/*if (!markerRegex.IsMatch(base.SelectedValue)) {
				while (base.MoveNext() && markerRegex.IsMatch(base.SelectedValue)) {
				}
			}

			StringBuilder markerHtmlBuilder = new StringBuilder();
			markerHtmlBuilder.Append(base.SelectedValue);

			while (base.MoveNext() && !markerRegex.IsMatch(base.SelectedValue)) {
				markerHtmlBuilder.Append(base.SelectedValue);
			}

			currentValue = markerHtmlBuilder.ToString();

			return Success;*/
		}

		public override bool Success {
			get {
				bool success = false;
				if (currentMatch != null && previousMatch != null) {
					success = currentMatch.Success || previousMatch.Success;
				}
				if (previousMatch == null && currentMatch != null) {
					success = currentMatch.Success;
				}

				return success;
			}
		}
	}
}
